import React, { useState, forwardRef, useEffect } from "react";
import { Button, TextArea, Grid, Avatar, Toast } from "antd-mobile";
import { MinusCircleOutline, AddCircleOutline, FileOutline, MovieOutline, PictureOutline } from "antd-mobile-icons";
import { useToggle } from "ahooks";
import styles from "./ChatEditor.less";
import Upload, { uploadFile } from "@/components/Upload";
import { ChatMessageType } from "../../../serve/interfaces";

const ChatEditor = (props: {
  disabled?: boolean;
  onSend: (type: ChatMessageType, body: string) => void
  txt?: string
}, ref) => {
  const [text, setText] = useState(props.txt || '');
  const [open, { toggle, setLeft }] = useToggle(false);
  const [disabled, setDisabled] = useState(false)
  let timer: NodeJS.Timer
  useEffect(function () {
    const disabled = props.disabled
    clearTimeout(timer)
    timer = setTimeout(function () {
      setDisabled(disabled)
    }, 500)
    return function () {
      clearTimeout(timer)
    }
  }, [props.disabled])

  useEffect(function () {
    if (props.txt) {
      setText(text + props.txt)
    }
  }, [props.txt])

  const onSend: typeof props.onSend = (type, body) => {
    if (type === ChatMessageType.TXT) {
      const _v = body.replace(/[\r\n\t\s]+/g, '')
      if (!_v) {
        Toast.show({
          icon: 'fail',
          content: '不能发送空内容'
        })
        return
      }
    }
    props.onSend(type, body)
  }
  return (
    <div ref={ref} className={styles["chat-editor-warp"]}
      style={{
        display: disabled ? 'none' : 'block',
      }}>
      <div className={styles["chat-text-area-warp"]} onKeyDown={e => {
        const shiftKey = /mobile/i.test(navigator.userAgent) || e.shiftKey
        if(!shiftKey && e.key === 'Enter') {
          e.preventDefault()
          onSend(ChatMessageType.TXT , text);
          setText("");
        }
      }} onPaste={async (e) => {
        if (e.clipboardData.files[0]) {
          const res = await uploadFile(e.clipboardData.files[0])
          if (res) {
            onSend(...res)
          }
        }
      }}>
        <TextArea
          disabled={props.disabled}
          className={styles["chat-text-area"]}
          placeholder="请输入内容"
          rows={1}
          autoSize={{ minRows: 1, maxRows: 5 }}
          value={text}
          onChange={(value) => {
            setText(value);
          }}
          onFocus={() => {
            setLeft();
          }}
        />
        <div style={{ marginLeft: "5px" }}>
          {text ? (
            <Button
              onClick={() => {
                onSend?.(ChatMessageType.TXT , text);
                setText("");
              }}
            >
              发送
            </Button>
          ) : (
            <Button style={{ borderColor: 'transparent', background: 'none' }} onClick={toggle} disabled={props.disabled}>
              <div style={{ transform: 'scale(1.5)' }}>
                {open ? <MinusCircleOutline/>  : <AddCircleOutline  />}
              </div>
            </Button>
          )}
        </div>
      </div>
      {open && (
        <div className={styles["chat-tool-area"]}>
          <Grid columns={6} gap={8}>
            <Grid.Item>
              <div className={styles["tool-item"]}>
                <Upload accept="image/*" onSuccess={url => onSend(ChatMessageType.IMG, url)}>
                  <Avatar src="" fallback={<PictureOutline fontSize={32}/>}/>
                  图片
                </Upload>
              </div>
            </Grid.Item>
            <Grid.Item>
              <div className={styles["tool-item"]}>
              <Upload accept="video/*" onSuccess={url => onSend(ChatMessageType.VIDEO, url)}>
                <Avatar src="" fallback={<MovieOutline fontSize={32}/>}/>
                视频
              </Upload>
              </div>
            </Grid.Item>
            <Grid.Item>
              <div className={styles["tool-item"]}>
              <Upload accept="*" onSuccess={url => onSend(ChatMessageType.FILE, url)}>
                <Avatar src="" fallback={<FileOutline fontSize={32}/>}/>
                文件
              </Upload>
              </div>
            </Grid.Item>
          </Grid>
        </div>
      )}
    </div>
  );
};

export default forwardRef(ChatEditor);
